package com.auth.exct;

import com.exception.bean.Result;
import com.exception.enu.ExceptionEnum;
import com.exception.util.DescribeException;
import com.exception.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * Created by Administrator on 2017/7/13 0013.
 * 错误定义
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public static Result exceptionGet(Exception e){
        if(e instanceof DescribeException){
            DescribeException pingjiaException = (DescribeException) e;
            return ResultUtil.error(pingjiaException.getCode(),pingjiaException.getMessage());
        }
        if(e instanceof MethodArgumentTypeMismatchException){
            logger.error("{}",e);
            return ResultUtil.error(ExceptionEnum.PARA_ERROR);
        }
        if(e instanceof IllegalStateException){
            logger.error("{}",e);
            return ResultUtil.error(-100,e.getMessage());
        }
        if(e  instanceof org.springframework.web.servlet.NoHandlerFoundException){
            logger.error("{}",e);
            return ResultUtil.error(404,e.getMessage());
        }
        if(e instanceof org.springframework.web.HttpRequestMethodNotSupportedException){
            logger.error("{}",e);
            return ResultUtil.error(405,e.getMessage());
        }


        logger.error("【系统异常】{}",e);
        return ResultUtil.error(ExceptionEnum.UNKNOW_ERROR);
    }

}
